//
//  STPNotificationCenter.swift
//  iPhone
//
//  Created by Toj on 2/23/23.
//
//  P == UserPush
//

import Foundation

struct UPPushKey {
    var rawValue: String
    
    static let firebaseMessageID = UPPushKey(rawValue: "gcm.message_id")
}

class STPNotificationCenter: NSObject {
    
    static let shared = STPNotificationCenter()
    
    private override init() {
        super.init()
    }
    
    public func setup() {
        AuthorizationManager.manager.at_registerPushNotifications()
        setupHandlers()
        resetBageNumber()
    }
    
    private func isAllow(_ completion: @escaping ((_ isAllow: Bool) -> Void)) {
        AuthorizationManager.manager.at_getNotificationSettings(completion: { isAllow in
            completion(isAllow)
            guard !isAllow else { return }
            AuthorizationManager.manager.openSettings()
        })
    }
    
    private func setupHandlers() {

        UNCenterManager.manager.setWillPresentResponceHandler { type, content in
            UIApplication.shared.applicationIconBadgeNumber += 1
            
            let subscribeId = content.categoryIdentifier
            let title = content.title
            let subtitle = content.subtitle
            let body = content.body
            let userInfo = content.userInfo
            let isShowAlert = userInfo["isShowAlert"] as? Bool ?? false
            print("-->toj: responceHandler: subscribeId: \(subscribeId)")
            print("-->toj: responceHandler: title: \(title)")
            print("-->toj: responceHandler: subtitle: \(subtitle)")
            print("-->toj: responceHandler: body: \(body)")
            print("-->toj: responceHandler: userInfo: \(userInfo)")
            print("-->toj: responceHandler: isShowAlert: \(isShowAlert)")
            return isShowAlert
        }
        
        UNCenterManager.manager.setDidReceiveResponceHandler { type, content in
            UIApplication.shared.applicationIconBadgeNumber -= 1
            
            let subscribeId = content.categoryIdentifier
            let title = content.title
            let subtitle = content.subtitle
            let body = content.body
            let userInfo = content.userInfo
            print("-->toj: responceHandler: subscribeId: \(subscribeId)")
            print("-->toj: responceHandler: title: \(title)")
            print("-->toj: responceHandler: subtitle: \(subtitle)")
            print("-->toj: responceHandler: body: \(body)")
            print("-->toj: responceHandler: userInfo: \(userInfo)")
            
            let appDelegate = UIApplication.shared.delegate as? AppDelegate
            let window = appDelegate?.window
            window?.makeToast("\(userInfo)", duration: 3, position: CSToastPositionCenter)
        }
    }
    
   private func resetBageNumber() {
       guard UIApplication.shared.applicationIconBadgeNumber > 0 else { return }
       UIApplication.shared.applicationIconBadgeNumber = -1
   }
}
